package com.gcloud.mesh.dcs.service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.exception.MyBusinessException;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.utils.MyValidatorUtils;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.msg.dcs.ImportClusterMsg;
import com.gcloud.mesh.header.msg.supplier.CreateSupplierMsg;
import com.gcloud.mesh.header.param.AliMigrationParam;
import com.gcloud.mesh.header.param.ClusterMigrationParam;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.ClusterVo;
import com.gcloud.mesh.sdk.gce.GcePageReply;
import com.gcloud.mesh.sdk.gce.ImportClusterVO;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.supplier.enums.SystemType;
import com.gcloud.mesh.supplier.service.SupplierService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service
public class ClusterService{

    @Autowired
    SupplierDao supplierDao;

    @Autowired
    SupplierService supplierService;

    @Autowired
    RedisUtil redisUtil;

    public Map<String,Object> queryList(String datacenterId) {
        Map<String,Object> result = Maps.newHashMap();
        GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
        GcePageReply<ClusterVo> clusterVoGcePageReply = gceSDK.pageCluster(1, Integer.MAX_VALUE);
        result.put("clusters",clusterVoGcePageReply.getData());
        result.put("info",supplierDao.findOneByProperty("datacenterId",datacenterId));
        return result;
    }

    public String importCluster(ImportClusterMsg importClusterMsg) {
        switch (SystemType.getSystemTypeByName(importClusterMsg.getType())){
            case K8S: {
                return importK8s(importClusterMsg);
            }
            case ALI:{
                return importAli(importClusterMsg);
            }
            case HUAWEI:{
                return importHuawei(importClusterMsg);
            }
            default:
                throw new MyBusinessException("国网云类型不正确");
        }
    }

    private String importHuawei(ImportClusterMsg importClusterMsg){
        HuaweiMigrationParam huaweiMigrationParam = importClusterMsg.getHuaweiMigrationParam();
        if(huaweiMigrationParam==null) throw new MyBusinessException("请填写华为云虚拟机信息");
        String datacenterId = importClusterMsg.getDatacenterId();
        String name = importClusterMsg.getName();
        String vmid = huaweiMigrationParam.getVmId();
        SupplierEntity supplierEntity = supplierDao.findOneByProperty("datacenterId", datacenterId, SupplierEntity.class);
        if(supplierEntity==null){
            //新增
            supplierEntity = new SupplierEntity();
            supplierEntity.setClusterId(vmid)
                    .setName(name)
                    .setType(SystemType.HUAWEI.getName())
                    .setDatacenterId(datacenterId)
                    .setId(UUID.randomUUID().toString())
                    .setConfig(JSONObject.toJSONString(huaweiMigrationParam));
            supplierDao.save(supplierEntity);
        }else{
            //更新
            supplierEntity.setClusterId(vmid)
                    .setName(name)
                    .setType(SystemType.HUAWEI.getName())
                    .setConfig(JSONObject.toJSONString(huaweiMigrationParam));
            supplierDao.update(supplierEntity);
        }
        return Strings.EMPTY;
    }

    private String importAli(ImportClusterMsg importClusterMsg){
        AliMigrationParam aliMigrationParam = importClusterMsg.getAliMigrationParam();
//        aliMigrationParam = new AliMigrationParam();
//        aliMigrationParam.setAccessKeyId("LTAI5tD5F828pRk2S18iUXKt");
//        aliMigrationParam.setAccessSecret("fQ8ff7lfncvQsPAVQPGQIT579djAL2");
//        aliMigrationParam.setInstanceId("i-7xv0j6qg6j86k87eva4j");
        if(aliMigrationParam==null) throw new MyBusinessException("请填写阿里云虚拟机信息");
        MyValidatorUtils.validateEntity(aliMigrationParam);
        String datacenterId = importClusterMsg.getDatacenterId();
        String name = importClusterMsg.getName();
        String instanceId = aliMigrationParam.getInstanceId();
        SupplierEntity supplierEntity = supplierDao.findOneByProperty("datacenterId", datacenterId, SupplierEntity.class);
        if(supplierEntity==null){
            //新增
            supplierEntity = new SupplierEntity();
            supplierEntity.setClusterId(instanceId)
                    .setName(name)
                    .setType(SystemType.ALI.getName())
                    .setDatacenterId(datacenterId)
                    .setId(UUID.randomUUID().toString())
                    .setConfig(JSONObject.toJSONString(aliMigrationParam));
            supplierDao.save(supplierEntity);
        }else{
            //更新
            supplierEntity.setClusterId(instanceId)
                    .setName(name)
                    .setType(SystemType.ALI.getName())
                    .setConfig(JSONObject.toJSONString(aliMigrationParam));
            supplierDao.update(supplierEntity);
        }
        return Strings.EMPTY;
    }


    private String importK8s(ImportClusterMsg importClusterMsg){
        ClusterMigrationParam clusterMigrationParam = importClusterMsg.getClusterMigrationParam();
        if(clusterMigrationParam==null) throw new MyBusinessException("请填写集群信息");
        MyValidatorUtils.validateEntity(clusterMigrationParam);
        String clusterId = clusterMigrationParam.getClusterId();
        String insecureCommand = "";
        if(StringUtils.isBlank(clusterId)){
            //接入国网
            if(StringUtils.isBlank(clusterMigrationParam.getClusterName())) throw new MyBusinessException("集群名称不能为空");
            ImportClusterVO cluster = getCluster(clusterMigrationParam.getClusterName());
            insecureCommand = cluster.getInsecureCommand();
            clusterId = cluster.getClusterId();
        }else{
            GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
            ClusterVo clusterVo = gceSDK.detailCluster(clusterId);
            if(clusterVo==null || clusterVo.getCluster()==null) throw new MyBusinessException("集群ID有误");
            SupplierEntity supplierEntity = supplierDao.findOneByProperty("clusterId", clusterId);
            Map<String,Object> prop = Maps.newHashMap();
            prop.put("datacenterId",importClusterMsg.getDatacenterId());
            prop.put("type",importClusterMsg.getType());
            SupplierEntity srcSe = supplierDao.findOneByProperties(prop);
            if(srcSe==null && supplierEntity!=null) throw new MyBusinessException("集群已被其他数据中心接入");
            if(srcSe!=null && supplierEntity!=null && !srcSe.getClusterId().equalsIgnoreCase(clusterId)) throw new MyBusinessException("集群已被其他数据中心接入");
            insecureCommand = clusterVo.getCluster().getInsecureCommand();
        }
        CreateSupplierMsg msg = new CreateSupplierMsg();
        BeanUtils.copyProperties(clusterMigrationParam,msg);
        List<String> config = Lists.newArrayList();
        Map<String,String> p = Maps.newHashMap();
        p.put("restveleroIp",clusterMigrationParam.getRestveleroIp());
        p.put("clusterId",clusterId);
        config.add(JSON.toJSONString(p));
        
        SupplierEntity supplier = new SupplierEntity();
        supplier.setId(UUID.randomUUID().toString());
        supplier.setDatacenterId(importClusterMsg.getDatacenterId());
        supplier.setName(importClusterMsg.getName());
        supplier.setInsecureCommand(insecureCommand);
        supplier.setType(importClusterMsg.getType());
        supplier.setClusterId(clusterId);
        supplier.setConfig(JSON.toJSONString(p));
        try {
        	supplierDao.save(supplier);
        }catch(Exception e) {
        	
        }
        
        return insecureCommand;
    }

    public ImportClusterVO getCluster(String name){
        try {
            GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
            ImportClusterVO importCluster = gceSDK.importCluster(name, "1", "1", "1");
            if(importCluster==null) throw new MyBusinessException("导入国网失败");
            redisUtil.set(String.format("gce:cluster:%s",name),JSON.toJSON(importCluster),60*60*24);
            return importCluster;
        }catch(Exception e){
            Object o = redisUtil.get(String.format("gce:cluster:%s", name));
            if(o!=null) return JSON.toJavaObject((JSON)JSONObject.toJSON(o),ImportClusterVO.class);
            throw new MyBusinessException("导入国网失败");
        }
    }
}
